<template>
	<view class="dispatchDevice">
		<!-- 资源调度 --- 调度设备 -->
		<view class="device">
			<view class="leftBox">
				<view class="stationName" @click="isShowStation = true"  v-if="!obj.stationName">
					请选择基地
				</view>
				<view class="stationName stationNameActive" @click="isShowStation = true"  v-else>
					{{ obj.stationName }}
				</view>
				<view class="device-type">
					<view class="item" v-for="item in deviceTypeList" :key="item.id" :class="{active: currentIndex === item.id}" @click="getSwitch(item)">{{ item.name }}</view>
				</view>
			</view>
			<view class="rightBox">
				<u--input
					prefixIcon="search"
					prefixIconStyle="font-size: 26px;color: #909399"
					class="input"
				   placeholder="请输入设备名称"
				   clearable
				   v-model="deviceName"
				   @change="deviceNameChange"
				 ></u--input>
				 
				<view class="uniCollapse">
					<uni-collapse class="collapse" v-model="collapseValue">
						<checkbox-group @change="checkboxChange">
							<uni-collapse-item  title-border="show" v-for="item in deviceNameList" :name="item.name" :key="item.name"  :title="item.name">
								<template v-slot:title>
									<view class="collapse-title">
										<view class="left">
											{{ item.name }}
										</view>
										<view class="right">
											{{ item.num }}
										</view>
									</view>
								</template>
								<view class="coll" v-for="value in item.children" :key="value.id">
									<view class="coll-item">
										<view class="name">规格型号： </view>
										<view class="value">{{ value.specificationModel }}</view>
									</view>
									<view class="coll-item">
										<view class="name">设备编号： </view>
										<view class="value">{{ value.code }}</view>
									</view>
									<view class="coll-item">
										<view class="name">所属基地： </view>
										<view class="value">{{ value.stationName }}</view>
									</view>
									<checkbox :value="value.id + ''" :checked="value.isChecked" :disabled="isDeviceDisabled" class="checkbox color round"></checkbox>
								</view>
							</uni-collapse-item>
						</checkbox-group>
					</uni-collapse>
				</view> 
			</view>
		</view>
		
		<u-picker 
			:show="isShowStation" 
			:columns="stationColumns"
			keyName="name"
			:closeOnClickOverlay="true"
			@confirm="stationConfirm" 
			@cancel="stationCancel">
		</u-picker>
	</view>
</template>

<script>
	import { getDeviceList, equipment_getListByDeviceTypeIdNoProjectId, getDeviceType, getShoppingCartEquipmentList, getShoppingCartBatchDelete, getShoppingCartBatchSave } from "@/api/emergency/emergencyDispatch.js";
	import uniCollapse from "./uni-collapse/components/uni-collapse/uni-collapse.vue";
	
	export default {
		name: "dispatchDevice",
		components: {
			uniCollapse
		},
		props: {
			stationList:{
				type: Array,
				default: ()=>[],
				required: true,
			},
			eventId: {
				type: Number,
				default: null,
				required: true,
			}
		},
		data() {
			return {
				isShowStation: false,
				deviceTypeList: [],   // 设备类型列表
				deviceNameList: [],   // 设备名称列表
				currentIndex: -1,
				stationColumns: [],    // 渲染的基地数据
				obj: {
					stationName: "",    // 选中的基地名称
					stationIds: [],     // 选中的基地id
				},
				deviceTypeIds: [],      // 选中的设备类型下, 所有的设备名称id
				deviceName: null,         // 设备名称模糊搜索
				isDeviceDisabled: false,   // 是否禁用,  在发送请求时, 不允许在此发送
				collapseValue: [],
			}
		},
		mounted() {
			// stationList 父组件传递过来的基地数据
			// 格式化基地数据
			let list = JSON.parse(JSON.stringify(this.stationList))
			this.stationColumns = [list]
			this.getDeviceType()
			this.getDeviceList()
		},
		methods: {
			// 获取设备类型数据
			async getDeviceType(){
				let res = await getDeviceType({name: "", ex1: "equipment"})
				this.tempDeviceList = res.result
				// 只获取层级为2 的设备类型
				this.deviceTypeList =  [{id: -1, name: "全部"},...res.result.filter(item => item.treeLevel === 2)]
			},
			
			// 获取设备列表数据
			async getDeviceList(){
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let _data = {
					eventId: this.eventId,
					stationIds: this.obj.stationIds,
					deviceTypeIds: this.deviceTypeIds,
					name: this.deviceName,
					typeIds:[102,104]
				}
				// this.deviceNameList = []
				let res = await equipment_getListByDeviceTypeIdNoProjectId(_data)
				
				// 获取回显数据
				let res2 = await getShoppingCartEquipmentList({eventId: this.eventId})
				// 把 回显数据存储起来
				this.deviceWarehouseList = JSON.parse(JSON.stringify(res2.result))
				// 根据条件过滤
				// 根据基地 过滤
				let tempList = res2.result.filter(item=> {
					// 判断 是否有基地 id
					if(this.obj.stationIds && this.obj.stationIds.length > 0){
						return this.obj.stationIds.find((value)=> value === item.stationId)
					}else{
						return true
					}
				})

				// 根据设备类型 设备名称 过滤
				let tempList2 = tempList.filter(item=> {
					// 判断 是否有基地 id
					if(this.deviceTypeIds && this.deviceTypeIds.length > 0){
						return this.deviceTypeIds.includes(item.subDeviceTypeId)
					}else{
						return true
					}
				})
				// 根据模糊搜索过滤
				let tempList3 = tempList2.filter(item=> {
					// 判断 this.deviceName 是否有值
					if(this.deviceName){
						console.log((item.name).includes(this.deviceName), this.deviceName, item.name);
						return (item.name).includes(this.deviceName)
						
					}else{
						return true
					}
				})
				// // 给回显数据,添加标识
				// tempList2.forEach(ele=>{
				// 	this.$set(ele,'isChecked',true)
				// })
				// res.result.forEach(ele=>{
				// 	this.$set(ele,'isChecked', false)
				// })
				let list = [...tempList3, ...res.result]
				list.forEach(ele=>{
					if(ele.eventCostId){
						this.$set(ele,'isChecked',true)
					}else{
						this.$set(ele,'isChecked', false)
					}
				})
				// 按照 基地名称排序 基地名称相同, 按照 材料名称排序, 材料名称相同 按照规格型号排序
				list.sort(function(val, item){
					if(val.stationName !== item.stationName){
						return val.stationName.localeCompare(item.stationName, "zh-CN")
					}
				
					if(val.name !== item.name){
						return val.name.localeCompare(item.name, "zh-CN")
					}
					return (val.specificationModel || "").localeCompare((item.specificationModel || ""), "zh-CN")
				})
				// console.log(list,'201行');
				// 格式化接口数据
				this.deviceNameList = await this.arrayFilter(this.filterUnique(list), "subDeviceTypeName")
				let collList = []
				this.deviceNameList.forEach((item)=>{
						collList.push(item.name)
				})
				// this.$nextTick(()=>{
				// 	this.collapseValue = collList
				// })
				
				uni.hideLoading();
				// console.log(this.deviceNameList,'deviceNameList');
				
			},
			//根据数组中对象的某个属性值进行去重
			filterUnique(arr) {
				const res = new Map()
				return arr.filter(item => !res.has(item.id) && res.set(item.id,1))
			},
			
			// 切换 设备类型选中
			getSwitch(item){
				this.currentIndex = item.id
				
				// 当选中的不是全部时, 过滤出点击的设备类型下, 所有子集设备名称id
				if(this.currentIndex !== -1){
					this.deviceTypeIds = this.tempDeviceList.filter(item=>item.parentId === this.currentIndex).map(value=>value.id)
					this.getDeviceList()
				}else{
					this.deviceTypeIds = []
					this.getDeviceList()
				}
			},
			
			// 多选框的change事件
			// 保存 删除设备
			async checkboxChange(val){
				// uni.showLoading({
				// 	title: '加载中',
				// 	mask: true
				// })
				if(this.isDeviceDisabled) return
				this.isDeviceDisabled = true
				let checkboxChecked = val.detail.value.map(item=> +item)
				let ids
				if(this.currentIndex !== -1){
					ids = this.deviceWarehouseList.filter(item=>item.deviceTypeId === this.currentIndex).map(item=>item.id)
				}else{
					ids = this.deviceWarehouseList.map(item=> item.id)
				}
				 
				let temp = []
				
				if(checkboxChecked.length > ids.length){
					temp = checkboxChecked.filter(item=>{
						return !ids.find(value=> item===value)
					})
				}else{
					temp = ids.filter(item=>{
						return !checkboxChecked.find(value=> item===value)
					})
				}
				console.log(checkboxChecked, ids, temp);
				// 在判断 temp 是否在 ids中 在就是删除,  不在就是添加
				if(temp.length > 0){
					if(ids.includes(temp[0])){
						let eventCostId = this.deviceWarehouseList.find(item=> item.id === temp[0]).eventCostId
						// 删除
						let _data = await getShoppingCartBatchDelete([eventCostId])
					}else{
						// 添加
						let list = [temp[0]].map(item=>{
							return{
								itemId: item,
								type: "equipment",
								num: 1,
								eventId: this.eventId,
							}
						})
						// 保存数据
						let res = await getShoppingCartBatchSave(list)
					}
					await this.getDeviceList()
					// 调用购物车列表接口, 刷新 购物车数量
					await this.$emit("shoppingList")
				}
				this.isDeviceDisabled = false
				// uni.hideLoading();
			},
			
			// 基地 confirm 事件
			stationConfirm(val){
				this.isShowStation = false
				// 保存 基地名称 基地id
				this.obj.stationName = val.value[0].name
				this.obj.stationIds = [val.value[0].id]
				this.getDeviceList()
			},
			
			// 基地cancel事件
			stationCancel(){
				// 取消选择基地  基地名称 基地id 重置
				this.isShowStation = false
				this.obj.stationName = ""
				this.obj.stationIds = []
				this.getDeviceList()
			},
			
			// 设备名称模糊搜索
			deviceNameChange(val){
				if(val.trim() === ""){
					this.deviceName = null
				}
				this.getDeviceList()
			},
			
			/**
			* @description:  list 数组根据 stationName分组 num统计数量
			* @param {type}  list: 需要处理的数组  (原数组)
			* @param {type}  stationName: 用于判断相同的键名 
			* @return:       返回值: 数组
			*/
			arrayFilter(list, stationName){
				let obj = {}
				let newList = []
				for (let i = 0; i < list.length; i++) {
					let item = list[i]
					let str = item[stationName]
					if(obj[str]){
						obj[str].push(item)
					}else{
						obj[str]=[]
						obj[str].push(item)
					}
				}
				// 对象转数组
				for (let key in obj) {
					let value = obj[key]
					let newkey = {name: key, num:value.length, children: value}
					newList.push(newkey)
				}
				return newList
			}
		}
	}
</script>

<style lang="scss" scoped>
	.dispatchDevice{
		height: 100%;
		background-color: #fff;
		.device{
			display: flex;
			padding-top: 10rpx;
			height: 100%;
			box-sizing: border-box;
			
			.leftBox{
				width: 250rpx;
				height: 100%;
				.stationName{
					height: 90rpx;
					text-align: center;
					line-height: 90rpx;
					color: #bbb;
					border: 2rpx solid #E2E5ED;
					cursor: pointer;
					margin-bottom: 20rpx;
					overflow: hidden; //超出的文本隐藏
					text-overflow: ellipsis; //溢出用省略号显示
					white-space: nowrap; //溢出则不换行
				}
				.stationNameActive{
					background-color: #2f80ed;
					border: none;
					color: #fff;
				}
				
				.device-type{
					font-weight: 600;
					font-size: 32rpx;
					text-align: center;
					background-color: #f5f7fa;
					padding-top: 15rpx;
					height: calc(100% - 120rpx);
					box-sizing: border-box;
					.item{
						height: 84rpx;
						line-height: 84rpx;
						font-family: Noto Sans Thai UI-Medium, Noto Sans Thai UI;
						color: #6A819E;
						cursor: pointer;
					}
					.active{
						color: #2f80ed;
						font-weight: 600;
					}
				}
				
			}
			.rightBox{
				flex: 1;
				height: 100%;
				width: calc(100% - 250px);
				padding-right: 30rpx;
				padding-left: 15rpx;
				box-sizing: border-box;
				overflow: auto;
				.input{
					width: 400rpx;
					height: 64rpx;
					margin-bottom: 20rpx;
				}
				.collapse{
					.coll{
						position: relative;
						margin-bottom: 20rpx;
						padding-bottom: 20rpx;
						border-bottom: 2rpx solid #E2E5ED;
						.coll-item{
							margin-top: 20rpx;
							display: flex;
							
							.name{
								margin-left: 25rpx;
							}
							.value {
								max-width: 240rpx;
								overflow: hidden;
								white-space: nowrap;
								text-overflow: ellipsis;
							}
						}
						.checkbox{
							position: absolute;
							top: 10rpx;
							right: 20rpx;
						}
					}
				}
			}
		}
	}
</style>